package com.db;

import org.apache.commons.dbcp.BasicDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.util.Properties;

public class DBUtils {
    private static ThreadLocal<Connection> threadLocal = new ThreadLocal<>();
    private static DataSource ds=null;
    public static void init(){
        //创建一个属性文件
        Properties properties = new Properties();
        String dbcpPath=DBUtils.class.getClassLoader().getResource("jdbc.properties").getPath();
        dbcpPath=dbcpPath.substring(1);
        System.out.println(dbcpPath);
        try {
            //加载属性文件
            properties.load(new FileInputStream(dbcpPath));
            ds= BasicDataSourceFactory.createDataSource(properties);
            System.out.println("数据库连接池加载成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConn(){
       Connection con= threadLocal.get();
        try {
            if(con==null || con.isClosed()){
                if(ds==null){
                    init();
                }
                con= ds.getConnection();
                threadLocal.set(con);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return con;
    }

}
